<template>
    <view class="container">
        <u-steps class="u-p-t-20" :list="numList" mode="number" :current="2" active-color="#ff5000"></u-steps>
        <view class="item-container">
            <view class="title">营业执照信息</view>
            <view class="content">
                <u-form :model="authInfoForm" ref="authInfoForm" label-width="270" :error-type="errorType">
                    <u-form-item label="法定代表人姓名：" prop="legal_name" required>
                        <u-input v-model="authInfoForm.legal_name" placeholder="请输入法定代表人姓名" :maxlength="20" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="法人代表身份证号：" prop="legal_id" required>
                        <u-input v-model="authInfoForm.legal_id" placeholder="请输入法人代表身份证号" :maxlength="18" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="法人身份证电子版：" prop="legal_img" required>
                        <u-upload :action="action" :header="header" :max-count="1" :file-list="legalImgFile"
                            @on-remove="legalImgRemove" @on-success="legalImgSuccess">
                        </u-upload>
                    </u-form-item>
                    <u-form-item label="营业执照编号：" prop="license_num" required>
                        <u-input v-model="authInfoForm.license_num" placeholder="请输入营业执照编号" :maxlength="30" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="营业执照所在地：" prop="license_region" required>
                        <u-input @click="showAddressSelector = true" disabled v-model="authInfoForm.license_address"
                            placeholder="请选择营业执照所在地" clearable></u-input>
                    </u-form-item>
                    <u-form-item label="营业执照详细地址：" prop="license_add" required>
                        <u-input v-model="authInfoForm.license_add" placeholder="请输入营业执照详细地址" :maxlength="100"
                            clearable></u-input>
                    </u-form-item>
                    <date-picker @onConfirm="handleEstablishDate"
                        :defaultValue="authInfoForm.establish_date ? authInfoForm.establish_date : defaultTime"
                        ref="establishDatePicker">
                        <u-form-item label="成立日期：" prop="establish_date" required>
                            <u-input @click="handledatePicker('establish_date')" disabled
                                v-model="authInfoForm.establish_date" placeholder="请选择成立日期"></u-input>
                        </u-form-item>
                    </date-picker>
                    <date-picker @onConfirm="handleLicenceStart"
                        :defaultValue="authInfoForm.licence_start ? authInfoForm.licence_start : defaultTime"
                        ref="licenceStartDatePicker">
                        <u-form-item label="营业执照有效期：" prop="licence_start" required>
                            <u-input @click="handledatePicker('licence_start')" disabled
                                v-model="authInfoForm.licence_start" placeholder="请选择开始日期"></u-input>
                        </u-form-item>
                    </date-picker>
                    <view class="u-m-t-20" style="margin-left: 270rpx;">至</view>
                    <date-picker @onConfirm="handleLicenceEnd"
                        :defaultValue="authInfoForm.licence_end ? authInfoForm.licence_end: defaultTime"
                        ref="licenceEndDatePicker">
                        <u-form-item prop="licence_end">
                            <u-input @click="handledatePicker('licence_end')" disabled
                                v-model="authInfoForm.licence_end" placeholder="结束日期,长期有效可不填"></u-input>
                        </u-form-item>
                    </date-picker>
                    <u-form-item label="法定经营范围：" prop="scope" required>
                        <u-input v-model="authInfoForm.scope" placeholder="请输入法定经营范围" :maxlength="100" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="营业执照电子版：" prop="licence_img" required>
                        <u-upload :action="action" :header="header" :max-count="1" :file-list="licenceImgFile"
                            @on-remove="licenceImgRemove" @on-success="licenceImgSuccess">
                        </u-upload>
                    </u-form-item>
                    <view class="title">一般纳税人证明</view>
                    <u-form-item label="一般纳税人证明：" prop="taxes_img">
                        <u-upload :action="action" :header="header" :max-count="1" :file-list="taxesImgFile"
                            @on-remove="taxesImgRemove" @on-success="taxesImgSuccess">
                        </u-upload>
                    </u-form-item>
                </u-form>
            </view>
        </view>
        <view class="next-btns u-text-center u-p-b-20">
            <u-button class="u-m-r-40" size="mini" @click="handleBackStep">上一步</u-button>
            <u-button size="mini" @click="handleNextStep">下一步</u-button>
        </view>
        <u-popup v-model="showAddressSelector" mode="bottom" closeable close-icon-size="20" border-radius="20">
            <region-picke @addressSelectorChanged="addressSelectorChanged"
                @closeRegionpicke="showAddressSelector = false" :show="showAddressSelector"></region-picke>
        </u-popup>
    </view>
</template>

<script>
    import * as API_Shop from '@/api/shop'
    import {
        Foundation,
        RegExp
    } from '@/ui-utils'
    import {
        api
    } from '@/config/config'
    import Cache, {
        Keys
    } from '@/utils/cache.js'
    export default {
        data() {
            const req_rule = (message, trigger) => ({
                required: true,
                message,
                trigger: [trigger || 'blur']
            });
            const len_rule = (min, max) => ({
                min,
                max,
                message: `'长度在 ${min} 到 ${max} 个字符`
            });
            return {
                numList: [{
                    name: '入驻协议'
                }, {
                    name: '基本信息'
                }, {
                    name: '认证信息'
                }, {
                    name: '资质信息'
                }, {
                    name: '店铺信息'
                }],
                authInfoForm: {
                    legal_name: '',
                    legal_id: '',
                    legal_img: '',
                    license_num: '',
                    license_region: '',
                    license_address: '',
                    license_add: '',
                    establish_date: '',
                    licence_start: '',
                    licence_end: '',
                    scope: '',
                    licence_img: '',
                    taxes_img: ''
                },
                rules: {
                    legal_name: [req_rule('请输入法定代表人姓名！'), len_rule(1, 20)],
                    legal_id: [
                        req_rule('请输入法定代表人身份证号！'),
                        {
                            validator: (rule, value, callback) => {
                                if (!RegExp.IDCard.test(value)) {
                                    callback(new Error('身份证号格式不正确'))
                                } else {
                                    callback()
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    legal_img: [req_rule('请上传法人身份证电子版！', 'change')],
                    license_num: [req_rule('请输入营业执照编号！')],
                    license_region: [{
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请选择营业执照所在地！'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }],
                    license_add: [req_rule('请填写营业执照详细地址！')],
                    establish_date: [req_rule('请选择成立日期！')],
                    licence_start: [
                        req_rule('请选择开始日期！'),
                        {
                            validator: (rule, value, callback) => {
                                if (this.authInfoForm.licence_end && value >= this.authInfoForm.licence_end) {
                                    callback(new Error('开始时间不能晚于结束时间！'))
                                } else {
                                    callback()
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                    licence_end: [{
                        validator: (rule, value, callback) => {
                            if (this.authInfoForm.licence_end && this.authInfoForm.licence_start && value <=
                                this.authInfoForm.licence_start) {
                                callback(new Error('结束时间不能早于开始时间！'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }],
                    scope: [req_rule('请输入法定经营范围！')],
                    licence_img: [req_rule('请上传营业执照电子版！', 'change')]
                },
                errorType: ['toast'],
                action: `${api.buyer}/uploaders`,
                header: {
                    Authorization: Cache.getItem(Keys.accessToken)
                },
                showAddressSelector: false, //地区选择弹出框是否显示
                legalImgFile: [],
                licenceImgFile: [],
                taxesImgFile: [],
                defaultTime: ''
            };
        },
        onLoad() {
            API_Shop.getApplyShopInfo().then(response => {
                response.establish_date = Foundation.unixToDate(response.establish_date, 'yyyy-MM-dd')
                response.licence_start = Foundation.unixToDate(response.licence_start, 'yyyy-MM-dd')
                response.licence_end = parseInt(response.licence_end) ? Foundation.unixToDate(response.licence_end, 'yyyy-MM-dd') : ''
                Object.keys(this.authInfoForm).forEach(key => this.authInfoForm[key] = response[key])
                this.legalImgFile = this.authInfoForm.legal_img ? [{
                    url: this.authInfoForm.legal_img
                }] : []
                this.licenceImgFile = this.authInfoForm.licence_img ? [{
                    url: this.authInfoForm.licence_img
                }] : []
                this.taxesImgFile = this.authInfoForm.taxes_img ? [{
                    url: this.authInfoForm.taxes_img
                }] : []
                this.authInfoForm.license_address = response.license_province &&
                    `${response.license_province || ''} ${response.license_city || ''} ${response.license_county || ''} ${response.license_town || ''}`
                this.authInfoForm.license_region = response.license_town_id && response.license_town_id != 0 ?
                    response.license_town_id : response.license_county_id
            })
        },
        onReady() {
            this.$refs.authInfoForm.setRules(this.rules);
            this.defaultTime = Foundation.unixToDate(new Date().getTime() / 1000, 'yyyy-MM-dd');
        },
        methods: {
            handledatePicker(type) {
                if (type === 'establish_date') {
                    this.$refs.establishDatePicker.show()
                } else if (type === 'licence_start') {
                    this.$refs.licenceStartDatePicker.show()
                } else if (type == 'licence_end') {
                    this.$refs.licenceEndDatePicker.show()
                }
            },
            // 成立日期
            handleEstablishDate(e) {
                this.authInfoForm.establish_date = e.dateValue
            },
            // 营业执照开始时间
            handleLicenceStart(e) {
                this.authInfoForm.licence_start = e.dateValue
            },
            // 营业执照结束时间
            handleLicenceEnd(e) {
                this.authInfoForm.licence_end = e.dateValue
            },
            // 营业执照所在地
            addressSelectorChanged(object) {
                const obj = {
                    last_id: object[object.length - 1].id,
                    addrs: object.map(key => {
                        return key.local_name
                    }).join(' ')
                }
                this.authInfoForm.license_region = obj.last_id
                this.authInfoForm.license_address = obj.addrs
            },
            // 法人身份证电子版
            legalImgSuccess(res) {
                this.authInfoForm.legal_img = res.url
            },
            legalImgRemove() {
                this.authInfoForm.legal_img = ''
            },
            // 营业执照电子版
            licenceImgSuccess(res) {
                this.authInfoForm.licence_img = res.url
            },
            licenceImgRemove() {
                this.authInfoForm.licence_img = ''
            },
            // 一般纳税人证明
            taxesImgSuccess(res) {
                this.authInfoForm.taxes_img = res.url
            },
            taxesImgRemove() {
                this.authInfoForm.taxes_img = ''
            },
            // 上一步
            handleBackStep() {
                uni.navigateBack()
            },
            // 下一步
            handleNextStep() {
                const params = JSON.parse(JSON.stringify(this.authInfoForm))
                this.$refs.authInfoForm.validate(valid => {
                    if (valid) {
                        params.establish_date = Foundation.dateToUnix(params.establish_date)
                        params.licence_start = Foundation.dateToUnix(params.licence_start)
                        if (params.licence_end) {
                            params.licence_end = Foundation.dateToUnix(params.licence_end)
                        }
                        API_Shop.applyShopStep(2, params).then(response => {
                            this.$u.route('/pages/shop/apply/financial-qualification')
                        })
                    }
                })
            }
        }
    }
</script>

<style lang="scss">
    .container {
        background-color: #FFFFFF;

        .item-container {
            border-top: 1px dashed #E1E1E1;
            margin: 20rpx 0;

            .title {
                margin: 20rpx 0;
                font-size: 40rpx;
                font-weight: 600;
                text-align: center;
            }

            .content {
                padding: 0 30rpx;
            }

            .licence-range {
                margin-left: 260rpx;
            }
        }
    }

    /deep/ {
        .u-form-item--left {
            width: 270rpx !important;
        }
    }
</style>
